package com.weizai.carshop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.weizai.carshop.common.context.BaseContext;
import com.weizai.carshop.common.enumeration.AppHttpCodeEnum;
import com.weizai.carshop.common.exception.BaseException;
import com.weizai.carshop.mapper.OrderMapper;
import com.weizai.carshop.model.dto.AliPayDto;
import com.weizai.carshop.model.dto.OrderDto;
import com.weizai.carshop.model.entiity.CartListEntity;
import com.weizai.carshop.model.entiity.OrderDetailEntity;
import com.weizai.carshop.model.vo.OrderInfoVo;
import com.weizai.carshop.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderDetailEntity> implements OrderService {

    /*
     * 创建订单方法
     * */
    @Override
    @Transactional
    public OrderInfoVo createOrder(OrderDto orderInfo) {
        // 处理数据
        List<CartListEntity> cartListEntities = BeanUtil.copyToList(orderInfo.getGoodsDetail(), CartListEntity.class);
        CartListEntity[] goodsDetail = cartListEntities.stream().toArray(CartListEntity[]::new);

        // 删除购物车中的订单
        List<Long> cartIds = Arrays.stream(goodsDetail).map(CartListEntity::getId).collect(Collectors.toList());
        Db.removeByIds(cartIds, CartListEntity.class);

        // 准备创建订单的数据
        OrderDetailEntity buildOrder = OrderDetailEntity.builder()
                .sn(UUID.randomUUID().toString().replace("-", ""))
                .address(orderInfo.getAddress())
                .state(1)
                .userId(BaseContext.getCurrentId())
                .goodsDetail(goodsDetail)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();

        baseMapper.insert(buildOrder);

        String subjectName = "威澳车居订单";

        // 算出总价格
        BigDecimal totalPrice = Arrays.stream(goodsDetail).map(CartListEntity::getTotalValue).reduce(BigDecimal.ZERO, BigDecimal::add);

        String url = "http://localhost:8081/user/alipay/pay?subject=" + subjectName + "&traceNo=" + buildOrder.getSn() + "&totalAmount=" + totalPrice + "";

        OrderInfoVo orderInfoVo = OrderInfoVo.builder()
                .url(url)
                .sn(buildOrder.getSn())
                .state(buildOrder.getState())
                .build();

        return  orderInfoVo;

    }

}
